package org.aileen.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.aileen.captcha.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;


@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    //将对象导入
    @Autowired
    private CaptchaProperties  captchaProperties;
    private static long VALID_DATE = 60*1000;

    @RequestMapping("/get")
    public void getCatcha(HttpServletResponse response, HttpSession session){
        ICaptcha captcha = CaptchaUtil.createLineCaptcha( captchaProperties.getWidth(),captchaProperties.getHeight());//从对象中获取宽度和高度
        try {
            captcha.write(response.getOutputStream());
            //设置前端禁止缓存
            response.setHeader("Pragma","No-cache");
            //设置前端图片返回格式
            response.setContentType("image/jpeg");
            //打印验证码
            System.out.println(captcha.getCode());
            //存储Session
            session.setAttribute(captchaProperties.getSession().getCode(),captcha.getCode());
            //存储验证时间
            session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());
            //Servlet的OutputStream记得自行关闭哦！
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //验证接口
    @RequestMapping("/check")
    public Boolean check(String captchaCode,HttpSession session){
        System.out.println("接收captchaCode"+captchaCode);
        //参数校验
        //判断用户输入验证码是否和Session存储的一致
        //是否在有效期内
        if(!StringUtils.hasLength(captchaCode)){
            return false;
        }

        String sessionCode = (String) session.getAttribute(captchaProperties.getSession().getCode());
        Long sessionDate = (Long) session.getAttribute(captchaProperties.getSession().getDate());
        if(captchaCode.equalsIgnoreCase(sessionCode)
            && sessionDate != null
                && (System.currentTimeMillis() - sessionDate) < VALID_DATE){
            return true;
        }
        return false;//
    }
}
